package cn.itcast.service.impl;

import cn.itcast.mapper.*;
import cn.itcast.pojo.*;
import cn.itcast.rabbitmq.service.RabbitmqService;
import cn.itcast.service.payService;
import cn.itcast.util.DoubleUtils;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@SuppressWarnings("ALL")
@Slf4j
@Service
public class PayServiceImpl implements payService {

    @Resource
    cn.itcast.mapper.accountMapper accountMapper;

    @Resource
    horsemanMapper horsemanMapper;

    @Resource
    rechargeMapper rechargeMapper;

    @Resource
    cn.itcast.mapper.userMapper userMapper;

    @Resource
    cn.itcast.mapper.withdrawMapper withdrawMapper;

    @Resource
    infoMapper infoMapper;

    @Resource
    gzhMapper gzhMapper;

    @Resource
    private RabbitmqService rabbitmqService;

    @Override
    public List<account> findHoresmanAccount(String openId) {
        accountExample aEx = new accountExample();
        accountExample.Criteria criteria = aEx.createCriteria();
        criteria.andOpenIdEqualTo(openId);
        criteria.andAccountTypeidEqualTo(1);
        List<account> accounts = accountMapper.selectByExample(aEx);
        return accounts;
    }

    @Override
    public horseman queryByOpenId(String openId) {
        horsemanExample horsemanExample = new horsemanExample();
        horsemanExample.Criteria criteria = horsemanExample.createCriteria();
        criteria.andOpenIdEqualTo(openId);
        List<horseman> horsemen = horsemanMapper.selectByExample(horsemanExample);
        if(horsemen.isEmpty()){
            return null;
        }else {
            return horsemen.get(0);
        }
    }

    @Override
    public account queryAccountByOpenId(String openid) {
        accountExample accountExample = new accountExample();
        accountExample.Criteria criteria = accountExample.createCriteria();
        criteria.andOpenIdEqualTo(openid);
        criteria.andAccountNumberEqualTo("0201");
        List<account> accounts = accountMapper.selectByExample(accountExample);
        if(accounts.isEmpty()){
            return null;
        }else {
            return accounts.get(0);
        }

    }

    @Override
    public List<recharge> findrechargeRecord(String openId) {
        rechargeExample rechargeExample = new rechargeExample();
        rechargeExample.Criteria criteria = rechargeExample.createCriteria();
        criteria.andOpenIdEqualTo(openId);
        return rechargeMapper.selectByExample(rechargeExample);
    }

    @Override
    public user queryByUserOpenId(String openid) {
        userExample userExample = new userExample();
        userExample.Criteria criteria = userExample.createCriteria();
        criteria.andOpenIdEqualTo(openid);
        List<user> users = userMapper.selectByExample(userExample);
        if(users.isEmpty()){
            return null;
        }else {
            return users.get(0);
        }
    }

    @Override
    public account queryAccountByOpenIdByUser(String openid) {
        accountExample accountExample = new accountExample();
        accountExample.Criteria criteria = accountExample.createCriteria();
        criteria.andOpenIdEqualTo(openid);
        criteria.andAccountNumberEqualTo("0101");
        List<account> accounts = accountMapper.selectByExample(accountExample);
        if(accounts.isEmpty()){
            return null;
        }else {
            return accounts.get(0);
        }

    }

    @Override
    public boolean updateHoresmanAccount(account account,double amount,withdraw withdraw) {
        account.setAccountMoneyBalance(DoubleUtils.sub(account.getAccountMoneyBalance(),amount));
        log.debug("提现后账户金额");
        log.debug(account.getAccountMoneyBalance().toString());
        int i = accountMapper.updateByPrimaryKeySelective(account);
        if(i==1){
            //修改提现记录状态
            withdraw.setState("已到账");
            withdraw.setBillTime(new Date());
            withdrawMapper.updateByPrimaryKeySelective(withdraw);
            return true;
        }else {
            return false;
        }
    }

    @Override
    public boolean updateUserAccount(account account,double amount,withdraw withdraw) {
        account.setAccountMoneyBalance(DoubleUtils.sub(account.getAccountMoneyBalance(),amount));
        log.debug("提现后账户金额");
        log.debug(account.getAccountMoneyBalance().toString());
        int i = accountMapper.updateByPrimaryKeySelective(account);
        if(i==1){
            //修改提现记录状态
            withdraw.setState("已到账");
            withdraw.setBillTime(new Date());
            withdrawMapper.updateByPrimaryKeySelective(withdraw);

            return true;
        }else {
            return false;
        }
    }

    @Override
    public withdraw createWithDraw(withdraw withdraw,String type) {
        int j = withdrawMapper.insertSelective(withdraw);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:MM:SS");
            if(StringUtils.isNotBlank(ObjectUtils.toString(withdraw.getApplyTime()))){
                withdraw.setApplyTime_string(sdf.format(withdraw.getApplyTime()));
            }
        if(j==1){
            log.debug("开始推送");
            //推送消息给管理员，提醒派单

            List<String> openIds = new ArrayList<>();
            //肖原
            openIds.add("oFPgIw_D9SUsvqsD_uA7dDxz3eKs");
            //杨远量
            openIds.add("oFPgIw8H0Qwdw5xdLLXEstgEwzCk");
            //黄小姐
            openIds.add("oFPgIw3mH9OaK3wMEl9WQMdkYZu4");
            //陆荣康
//            openIds.add("oFPgIw9PIVwv02aCzZ2IX8J8CAHM");
            //冯多飞
            openIds.add("oFPgIw_Xd7UWBrgJpZSyoDPJ4e8Y");
            //冯成
            openIds.add("oFPgIw2-8r79J6aoNrtlhA9EQzn4");
            //王总
            openIds.add("oFPgIw4m20hoEXIELztoUQM3YdtU");


            //1，配置
            WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();
            wxStorage.setAppId("wx8153b9b18ebfa8eb");
            wxStorage.setSecret("c8bf9f0c564f7f44a297054995e6eada");
            String token = gzhMapper.selectByPrimaryKey(3).getAccessToken();
            wxStorage.setAccessToken(token);

            WxMpService wxMpService = new WxMpServiceImpl();
            wxMpService.setWxMpConfigStorage(wxStorage);


            //判断是骑手提现还是用户提现


            for (int i = 0 ;i<openIds.size() ;i++){
                WxMpTemplateMessage.MiniProgram miniProgram = new WxMpTemplateMessage.MiniProgram();
                miniProgram.setAppid("wx51d55df222d9901e");
                miniProgram.setPagePath("pages/towithdraw/index?id="+withdraw.getId());
                //2,推送消息
                WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                        .toUser(openIds.get(i))//要推送的用户openid
                        .templateId("cSmgAFlToOdXhkBhwxNl_mxX9DgkgHHd8Sg_91_O0Tc")//模版id
                        .miniProgram(miniProgram)
                        .build();
                //3,如果是正式版发送模版消息，这里需要配置你的信息
                templateMessage.addData(new WxMpTemplateData("first", "您有一条提现待审核记录，金额为："+withdraw.getNum(), "#ff0000"));
                templateMessage.addData(new WxMpTemplateData("keyword1", withdraw.getName()+"("+type+")"));
                templateMessage.addData(new WxMpTemplateData("keyword2", withdraw.getNumber()));
                templateMessage.addData(new WxMpTemplateData("keyword3", withdraw.getApplyTime_string(), "#FF00FF"));
                templateMessage.addData(new WxMpTemplateData("remark", "点击进入审核"));
                //templateMessage.addData(new WxMpTemplateData("name2", value2, color2));
                try {
                    wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
                } catch (Exception e) {
                    System.out.println("推送失败：" + e.getMessage());
                    e.printStackTrace();
                }
            }
            //添加消息记录
            info info = new info();
            info.setOpenid(withdraw.getOpenId());
            info.setInfoTitle("申请提现提醒");
            info.setInfoType("提现消息");
            info.setInfoContent("您申请的提现金额:"+withdraw.getNum()+"正在审核中，请耐心等待，审核时间为1-3个工作日。");
            info.setInfoImg("https://www.dhnep.cn:8181/dhn/icon/money-icon.png");
            info.setInfoTime(new Date());

            infoMapper.insertSelective(info);

            //发送提现申请通知消息
            this.rabbitmqService.sendWithdrawRemind(withdraw.getOpenId(),String.valueOf(withdraw.getNum()));

            return withdraw;
        }else {
            return null;
        }
    }

    @Override
    public List<withdraw> findWithdrawRecord(String openId) {
        withdrawExample wEx = new withdrawExample();
        wEx.setOrderByClause("apply_time DESC");
        withdrawExample.Criteria criteria = wEx.createCriteria();
        criteria.andOpenIdEqualTo(openId);
        return withdrawMapper.selectByExample(wEx);

    }

    @Override
    public withdraw createWithDrawByHoresman(withdraw withdraw) {
        return null;
    }

}
